﻿Imports System.Activities
Imports System.Reflection
Imports System.Xaml

''' <remarks>http://blogs.msdn.com/b/tilovell/archive/2011/02/19/secrets-of-the-xaml-build-task.aspx</remarks>
Public Class XamlActivityInitializer

    Public Shared Sub Initialize(ByVal act As Activity)

        Dim actType = act.GetType
        Dim resStream = actType.Assembly.GetManifestResourceStream(actType.FullName + ".xaml")
        If resStream Is Nothing Then
            Throw New InvalidOperationException("Resource not found")
        End If
        Dim schContext = CreateSchemaContext(actType.Assembly)
    End Sub

    Private Shared Function CreateSchemaContext(ByVal asm As Assembly) As XamlSchemaContext
        Dim asms = LoadAssemblies()
        asms.Add(Assembly.GetExecutingAssembly)
        asms.Add(asm)
        Return New XamlSchemaContext(asms)
    End Function

    Private Shared Function LoadAssemblies() As IList(Of Assembly)
        Dim asmNames As New List(Of String)
        asmNames.Add("'Microsoft.VisualBasic, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
        asmNames.Add("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        asmNames.Add("System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
        asmNames.Add("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        asmNames.Add("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        asmNames.Add("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        asmNames.Add("System.ServiceModel.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
        asmNames.Add("System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        asmNames.Add("System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        asmNames.Add("System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        asmNames.Add("System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

        Dim asmResult = asmNames.Select(Function(name)
                                            Return Load(name)
                                        End Function).ToList

        Return asmResult
    End Function

    Private Shared Function Load(ByVal asmNameVar As String) As Assembly

        Dim asmName As New AssemblyName(asmNameVar)
        Dim pubToken = asmName.GetPublicKeyToken
        Try
            Return Assembly.Load(asmName.FullName)
        Catch ex As Exception
            Dim shtName As New AssemblyName(asmName.Name)
            If pubToken IsNot Nothing Then
                shtName.SetPublicKeyToken(pubToken)
            End If
            Return Assembly.Load(shtName)
        End Try

    End Function

End Class
